const db = require("../../database");
const writeLogs = require('./writeLogs');

module.exports = (req, res) => {
    const {friendName, remarks} = req.body;
    const username = req.auth.username;
    let sql = 'select messages from users where username = ?';
    db.query(sql, friendName, (err, data) => {
        if (err) return res.cc(err)
        if (!data.length) return res.cc('用户不存在');
        let messages = JSON.parse(data[0].messages || '{}');
        if (messages[username]) {
            messages[username]['add'] = remarks;
        } else {
            messages[username] = {add: remarks};
        }
        messages = JSON.stringify(messages);
        sql = 'update users set messages = ? where username = ?';
        db.query(sql, [messages, friendName], (err, data) => {
            if (err) return res.cc(err)
            if (!data.affectedRows) return res.cc('消息更新失败');
            writeLogs('request', {
                username,
                req: `添加${friendName}为好友，备注内容为${remarks}`,
            })
            res.cc('请求成功', 0);
        })
    })
}